﻿using Opc.Ua;
using Opc.Ua.Configuration;
using SD.Infrastructure;
using SD.OpcServer.Host.Services;
using System;

namespace SD.OpcServer.Host
{
    /// <summary>
    /// 服务启动器
    /// </summary>
    public class ServiceLauncher
    {
        /// <summary>
        /// OPC应用实例
        /// </summary>
        private readonly ApplicationInstance _opcApplication;

        /// <summary>
        /// OPC服务契约主机
        /// </summary>
        private readonly System.ServiceModel.ServiceHost _opcServerContractHost;

        /// <summary>
        /// 构造器
        /// </summary>
        public ServiceLauncher()
        {
            this._opcApplication = new ApplicationInstance
            {
                ApplicationType = ApplicationType.Server,
                ConfigSectionName = FrameworkSection.Setting.ServiceDisplayName.Value
            };

            this._opcServerContractHost = new System.ServiceModel.ServiceHost(typeof(OpcServerContract));
        }

        /// <summary>
        /// 开始
        /// </summary>
        public void Start()
        {
            //初始化OPC服务
            Startup.ConfigureServices(this._opcApplication);

            //初始化WCF服务
            this._opcServerContractHost.Open();

            Console.WriteLine("服务已启动...");
            foreach (string address in this._opcApplication.ApplicationConfiguration.ServerConfiguration.BaseAddresses)
            {
                Console.WriteLine($"Listening: {address}");
            }
        }

        /// <summary>
        /// 停止
        /// </summary>
        public void Stop()
        {
            //关闭OPC服务
            this._opcApplication?.Stop();

            //关闭WCF服务
            this._opcServerContractHost.Close();

            Console.WriteLine("服务已关闭...");
        }
    }
}
